package org.jeecg.modules.solitaire_app.app.schedul;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.solitaire_app.app.entity.YsyOilCityPrice;
import org.jeecg.modules.solitaire_app.app.service.IYsyOilCityPriceService;
import org.jeecg.modules.solitaire_app.app.service.IYsyWithdrawLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

//@EnableScheduling
@RequestMapping("/app/test")
@RestController
public class YsyOilCityPriceSecheduling {

    @Autowired
    private IYsyOilCityPriceService ysyOilCityPriceService;

    //每月一号早上一点执行
//    @Scheduled(cron = "0 1 0 1 * ?")
    @GetMapping("/test")
    public void toUserFreeToUseMoney() {

        String url = "https://datacenter.cngold.org/city_oil/all_price_by_year/";

        String response = HttpRequest.get(url).execute().body();
        JSONObject resJson = new JSONObject(response);
        JSONArray resJsonArr = resJson.getJSONArray("data");
        List<YsyOilCityPrice> ysyOilCityPrices = new ArrayList<>();
        for (int i = 0; i < resJsonArr.size(); i++) {
            YsyOilCityPrice ysyOilCityPrice = new YsyOilCityPrice();
            BeanUtil.copyProperties(resJsonArr.getJSONObject(i), ysyOilCityPrice);
            ysyOilCityPrices.add(ysyOilCityPrice);
        }

        if (ysyOilCityPrices.size() > 0) {
            //先删除
            ysyOilCityPriceService.remove(Wrappers.<YsyOilCityPrice>lambdaQuery());
            //再添加
            ysyOilCityPriceService.saveBatch(ysyOilCityPrices);
        }
    }
}
